package com.qianli.cashmama.trade.openApi.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qianli.cashmama.trade.openApi.utils.encryption.ReceiveData;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author: cashmama
 * @Date: 2020/12/11-10:16
 * @Description: TODO
 * @Slogan: To be or not to be
 **/
@Component
@Log4j2
public class RequestInterceptor extends HandlerInterceptorAdapter {
    private static final String JSXM_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkRHFhZ2OZM17YFrE/4X/HgamSw4bIOdY8OCpzlqyDC06ICMh4AnlBoBu7pDTzBP0BcefBDCic4tf+X1yx3nrTTrddaVLJ0WTdae7ZOEdgY8MAa/w/iD78rD0Gp42lN1Vf46GQlHLbQeb7Kr1LViKt3YF+SBre2DV8Dp6063KmVwIDAQAB";

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");

//        String reqStr = this.convertReqStr(req);

//        log.info("＝＝＝＝＝＝＝＝＝＝＝＝＝>dispatcher receive:" + reqStr);
//        if (StringUtils.isNotEmpty(reqStr)) {
//            ReceiveData receiveData = JSONObject.parseObject(reqStr, ReceiveData.class);
//            String bizEnc = receiveData.getBiz_enc();
//            if (bizEnc.equals("1")) {
//                String sign = receiveData.getSign();
//                String jsonDataSorted = StandardUtil.getSignParamStr(reqStr);
//                return StandardUtil.checkSign(jsonDataSorted, sign, JSXM_PUBLIC_KEY);
//            }
//        }
//        return false;
        return true;
    }

    public static void main(String[] args) {
        String s = JSON.toJSONString(new ReceiveData());
        Object o = JSON.toJSON(ReceiveData.class);
        System.out.println();
    }

    private String convertReqStr(HttpServletRequest req) throws IOException {
        StringBuilder sb = new StringBuilder();
        List<String> lineList = IOUtils.readLines(req.getInputStream(), "utf-8");
        if (!lineList.isEmpty()) {
            for (String line : lineList) {
                sb.append(line);
            }
        }
        if (StringUtils.isNotBlank(sb.toString())) {
            return sb.toString();
        }
        return null;

    }
}
